<template>
  <div class="app-container">
    <!--查询  -->
    <el-row>
      <el-input style="width:200px" v-model="tableQuery.channelName" placeholder="应用名称"></el-input>
      <span style="margin-right: 15px"></span>
      <el-tooltip class="item" content="搜索" placement="top" >
        <el-button icon="el-icon-search" circle @click="fetchData()" v-perm="'b:applychannel:query'"></el-button>
      </el-tooltip>
    </el-row>
    <div style="margin-bottom: 30px"></div>
    <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleCreate" v-perm="'b:applychannel:add'">新增应用</el-button>
      <el-button type="primary" icon="el-icon-tickets" size="mini" @click="exportExcel" v-perm="'b:applychannel:exp'">导出</el-button>
    <div style="margin-bottom: 30px"></div>
    <!--列表-->
    <el-table style="width: 100%"
              :data="tableData"
              ref="xlsxtable"
              id="xlsxtable"
              v-loading.body="tableLoading"
              element-loading-text="加载中"
              border fit highlight-current-row>
               <el-table-column prop="id" label="应用id"></el-table-column>
      <el-table-column prop="channelCode" label="应用代码"></el-table-column>
      <el-table-column prop="channelName" label="应用名称"></el-table-column>
      <el-table-column prop="inputCode" label="拼音码"></el-table-column>
       <el-table-column prop="sortNo" label="排序"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-tooltip content="编辑" placement="top">
            <el-button @click="handleUpdate(scope.row)" size="medium" type="info" icon="el-icon-edit" circle plain v-perm="'b:applychannel:edit'"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top" >
            <el-button @click="handleDelete(scope.$index,scope.row)" size="medium" type="danger" icon="el-icon-delete" circle plain v-perm="'b:applychannel:del'" ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
      
    
    </el-table>
    <div style="margin-bottom: 30px"></div>
    <!--分页-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="tablePage.current"
      :page-sizes="[10, 20, 30, 40, 50]"
      :page-size="tablePage.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tablePage.total">
    </el-pagination>
    <!--弹出窗口：新增/编辑用户-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="20%">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="120px">
        <el-form-item label="所属机构" prop="orgId">
          <el-select v-model="temp.orgId"  placeholder="请选择" :disabled="this.orgId !== '0'">
            <el-option v-for="org in orgData" :key="org.id" :value="org.id" :label="org.orgName">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="应用代码" prop="channelCode">
          <el-input v-model="temp.channelCode"></el-input>
        </el-form-item>

        <el-form-item label="应用名称" prop="channelName">
          <el-input v-model="temp.channelName"></el-input>
        </el-form-item>

        <el-form-item label="拼音码" prop="inputCode">
          <el-input  v-model="temp.inputCode"></el-input>
        </el-form-item>

        <el-form-item label="排序" prop="">
           <el-input-number v-model="temp.sortNo"></el-input-number>
        </el-form-item>
       

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">创建</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
  

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import optionApi from '@/api/option'
import applychannelApi from '@/api/applychannel'
import { parseTime, resetTemp } from '@/utils'
import { root, confirm, pageParamNames } from '@/utils/constants'
import debounce from 'lodash/debounce'
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
export default {

  name: 'applychannelMessage',

  data() {
   
    return {
      parseTime: parseTime,
      tableLoading: false,
      tableData: [],
      orgData: [],
       orgMap: new Map(),
      tableQuery: {
        channelName: null
      },
      tablePage: {
        current: null,
        pages: null,
        size: null,
        total: null
      },
      dialogFormVisible: false,
      editRolesDialogVisible: false,
      dialogStatus: '',
      temp: {
        idx: null, // tableData中的下标
        id: null, // tableData中的下标
        orgId: null,
        channelCode: null,
        channelName: null,
        inputCode: null,
        sortNo: null,
        delete: null
      },
      textMap: {
        update: '编辑应用',
        create: '新增应用'
      },
      rules: {
       orgId: [
          { required: true, message: '所属机构不能为空', trigger: 'blur' }
        ],
         channelCode: [
          { required: true, message: '应用代码不能为空', trigger: 'blur' }
        ],
        channelName:[
          { required: true, message: '应用名称不能为空', trigger: 'blur' }
        ],
        inputCode:[
          { required: true, message: '拼音码不能为空', trigger: 'blur' }
        ]
      },
      checkAll: false,
      isIndeterminate: true,
      // 所有角色(管理员除外)
      roleOptions: [],
      roleMap: new Map(),
      // 更新用户的角色的数据
      updateUserRolesData: {
        idx: null,
        uid: null,
        rids: []
      }
    }
  },
 computed: {
    ...mapGetters([
      'orgId',
      'name',
      'nick',
      'avatar',
      'roles',
      'perms'
    ])
  },
  created() {
    this.initData()
    this.fetchData()
  },

  watch: {
    // 延时查询
    'tableQuery.channelName': debounce(function() {
      this.fetchData()
    }, 500)
  },
  // watch
  methods: {

    //导出
      exportExcel () {
        // alert("111");
        this.downloadLoading = true
         /* generate workbook object from table */
        //  var wb = XLSX.utils.table_to_book(this.$refs.xlsxtable)
         /* get binary string as output */
         var wb = XLSX.utils.table_to_book(document.querySelector('#xlsxtable'))
         var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
         try {
             FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '应用渠道信息.xlsx')
         } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
         return wbout
         this.downloadLoading = false
     },

    initData() {
      // 所有角色选项
      optionApi.listRoleOptions().then(res => {
        res.data.options.forEach(obj => {
          if (obj.val2 !== root.rval) {
            // 排除管理员
            this.roleOptions.push(obj)
            this.roleMap.set(obj.id, obj.val)
          }
        })
      })
      //所有机构信息
       optionApi.listOrgOptions().then(res => {
        console.log(res)
        res.data.orgOptions.forEach(obj => {
          this.orgData.push(obj)
          this.orgMap.set(obj.id, obj.orgName)
        })
      })
    },

    hasAdminRole(row) {
      if (row && row.roleList) {
        return row.roleList.some(role => role.rval === root.rval)
      }
      return false
    },

    // 全选
    handleCheckAllChange(val) {
      const allRids = this.roleOptions.map(role => role.id)
      this.updateUserRolesData.rids = val ? allRids : []
      this.isIndeterminate = false
    },

    // 分页
    handleSizeChange(val) {
      this.tablePage.size = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.tablePage.current = val
      this.fetchData()
    },

    // 查询
    fetchData(current) {
      if (current) {
        this.tablePage.current = current
      }
      this.tableLoading = true
      applychannelApi.queryApply(this.tableQuery,this.tablePage).then(res => {
        this.tableData = res.data.page.records
        this.tableLoading = false
        pageParamNames.forEach(name => this.$set(this.tablePage, name, res.data.page[name]))
      })
    },

    // 更新
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
    //   this.tempid.id = 
      // this.temp.channelCode = null
      // this.temp.channelName = null
      // this.temp.inputCode = null
      // this.temp.sortNo = null
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => this.$refs['dataForm'].clearValidate())
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) return
        const tempData = Object.assign({}, this.temp)// copy obj
        applychannelApi.update(tempData).then(res => {
          tempData.updated = res.data.updated
          this.tableData.splice(tempData.idx, 1, tempData)
          this.dialogFormVisible = false
          this.$message.success('更新成功')
        })
      })
    },
  
    // 删除
    handleDelete(idx,row) {
      this.$confirm('您确定要永久删除该用户？', '提示', confirm).then(() => {
        applychannelApi.delete({ id: row.id }).then(res => {
          this.tableData.splice(idx, 1)
          --this.tablePage.total
          this.dialogFormVisible = false
          this.$message.success('删除成功')
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 新增
    handleCreate() {
      resetTemp(this.temp)
      // this.temp = Object.assign({}, row) // copy obj
      //  console.log(this.orgId);
      if(this.orgId != '0'){
      this.temp.orgId  =  this.orgId  
      }
      this.temp.sortNo = this.tablePage.total + 1
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) return
        applychannelApi.add(this.temp).then((res) => {
          this.temp.id = res.data.id// 后台传回来新增记录的id
          this.tableData.unshift(Object.assign({}, this.temp))
          ++this.tablePage.total
          this.dialogFormVisible = false
          this.$message.success('添加成功')
        })
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.role-checkbox {
  margin-left: 0px;
  margin-right: 15px;
}
.el-select {
    width:200px;
  }
  .el-input {
    width: 200px;
  }
</style>
